package reflect;

import java.lang.reflect.Field;

/**
 *通过反射机制访问属性
 *
 */
public class ReflectDemo7 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class cls = Class.forName("reflect.Person");
        Object obj = cls.newInstance();//创建对象

        Field field = cls.getDeclaredField("name");
        field.setAccessible(true);
        field.set(obj,"张三");
        String name = (String) field.get(obj);
        System.out.println("姓名："+name);
        field.setAccessible(false);

        Field field1 = cls.getDeclaredField("age");
        field1.setAccessible(true);
        field1.set(obj,18);
        int age = (int)field1.get(obj);
        System.out.println("年龄："+age);
        field1.setAccessible(false);
    }
}
